# -*- coding: utf-8 -*-
#    CoreDesk - a powerfull jabber client
#    Copyright (C) 2009  Jean-Baptiste Gury <jeanbaptiste.gury@gmail.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
import os
import os.path
import sqlite3
import logging
import operator

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='d:/temp/coredesk.log',
                    filemode='w')


logger = logging.getLogger('CoreDeskTools')
def getHomeDir():
    if os.environ.has_key('HOME'):
        home_dir = os.environ['HOME']
    elif os.environ.has_key('HOMESHARE'):
        home_dir = os.environ['HOMESHARE']
    elif os.environ.has_key('HOMEDRIVE'):
        home_dir = "".join(os.environ['HOMEDRIVE']).join(os.environ['HOMEPATH'])
    else:
        home_dir = r'C:\temp'
    return unicode(home_dir)
    
def getCoredeskDir():
    dir = os.path.join(getHomeDir(), u'.coredesk')
    logger.debug(u"dir = " + unicode(dir))
    if not os.path.exists(dir):
        os.mkdir(dir)
    return dir
	
##def getSessionDB(id):
##    dir = getCoredeskDir()
##    pathSession = os.path.join(dir, id)
##    if not os.path.exists(pathSession):
##        createSessionDataBase(id)
##    db = os.path.join(pathSession,  u"cd"+id+u".db")
##    conn = sqlite3.connect(db)
##    return conn

def createSessionDataBase(id):
    dir = getCoredeskDir()
    pathSession = os.path.join(dir, id)
    if not os.path.exists(pathSession):
        os.mkdir(pathSession)
    db = os.path.join(pathSession,  u"cd"+id+u".db")
    conn = sqlite3.connect(db)
    cur = conn.cursor()
    try :
        cur.execute('''create table account (id integer primary key autoincrement, id_jid integer, description text, server text, port integer, resource text, avatar blob, password text)''')
        cur.execute('''create table contact (id integer primary key autoincrement, firstname text, lastname text, pseudo text)''')
        cur.execute('''create table jid (id integer primary key autoincrement, jid text, id_account integer)''')
        cur.execute('''create table association_contact_jid (id integer primary key autoincrement, id_contact, id_jid)''')
        cur.execute('''create table history (id integer primary key autoincrement, date text, heure text, from_id integer, to_id integer, content text)''')
        conn.commit()
        cur.close()
        return conn
    except Exception :
        logger.exception(u'Exception caught when initializing session.')

def encodePassword(password):
    return u"".join([unichr(operator.xor(ord(c),0xa5)) for c in unicode(password)])
